package com.agrimall.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.sql.DataSource;
import java.io.InputStream;

/**
 * MyBatis工具类
 */
public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    
    static {
        try {
            // 确保DBUtil先初始化
            DataSource dataSource = DBUtil.getDataSource();
            
            // 加载MyBatis配置文件
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            
            // 先构建基础配置
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            org.apache.ibatis.session.Configuration configuration = builder.build(inputStream).getConfiguration();
            
            // 设置数据源环境
            configuration.setEnvironment(
                new org.apache.ibatis.mapping.Environment(
                    "development",
                    new org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory(),
                    dataSource
                )
            );
            
            // 重新构建SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MyBatis初始化失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取SqlSession
     */
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
    
    /**
     * 获取SqlSession（自动提交）
     */
    public static SqlSession getSqlSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);
    }
}

